
#include "gt_util.h"

#include <cstring>
#include <pcre.h>
#if __linux
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif

#include "gt_entry.h"

#define config_dir "greptui"
#define config_file "greptui.rc"

// ok
int is_selectable(search_t *search, int index) {
  entry_t *ptr = search->result->start;

  for (int i = 0; i < index; i++)
    ptr = ptr->next;

  return is_entry_selectable(ptr);
}

// ok
char *regex(option_t *option, char *line, const char *pattern) {
  int ret;
  const char *pcre_error;
  int pcre_error_offset;
  int substring_vector[30];
  const char *matched_string;

  if (!option->pcre_compiled) {
    option->pcre_compiled =
        pcre_compile(pattern, 0, &pcre_error, &pcre_error_offset, NULL);
    if (!option->pcre_compiled)
      return NULL;

    option->p_extra = pcre_study(option->pcre_compiled, 0, &pcre_error);

    if (pcre_error)
      return NULL;
  }

  ret = pcre_exec(option->pcre_compiled, option->p_extra, line, strlen(line), 0,
                  0, substring_vector, 30);

  if (ret < 0)
    return NULL;

  pcre_get_substring(line, substring_vector, ret, 0, &matched_string);

  return (char *)matched_string;
}

// ok
char *strstr_wrapper(option_t *option, char *line, const char *pattern) {
  return strstr(line, pattern);
}

// ok
char *strcasestr_wrapper(option_t *option, char *line, const char *pattern) {
  return strcasestr(line, pattern);
}

// ok
void *from_options_to_parser(option_t *option) {
  parser_t parser;

  if (!option->incase_option)
    parser = (parser_t)strstr_wrapper;
  else
    parser = (parser_t)strcasestr_wrapper;

  if (option->regexp_option)
    parser = (parser_t)regex;

  return (void *)parser;
}